﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace Jemgine.Gui
{  
    public class Driver
    {
        public delegate void DrawItem(Rectangle Rect, bool MouseHover);
        public delegate void ClickHandler();

        internal MouseState nextMouseState;
        internal MouseState previousMouseState;

        private ClickHandler Action;

        public void BeginUI(MouseState NextMouseState)
        {
            previousMouseState = nextMouseState;
            nextMouseState = NextMouseState;
            Action = null;
        }

        public void EndUI()
        {
            if (Action != null) Action();
        }

        public void Button(Rectangle rect, DrawItem render, ClickHandler handle)
        {
            if (rect.Inside(nextMouseState.X, nextMouseState.Y))
            {
                render(rect, true);
                if (nextMouseState.LeftButton == ButtonState.Released && previousMouseState.LeftButton == ButtonState.Pressed)
                    Action = handle;
            }
            else
                render(rect, false);
        }

        public void MaskedButton(Rectangle rect, Func<float, float, bool> MaskQuery, DrawItem render, ClickHandler handle)
        {
            if (rect.Inside(nextMouseState.X, nextMouseState.Y))
            {
                Vector2 RelativeMouse = new Vector2(nextMouseState.X - rect.X, nextMouseState.Y - rect.Y);
                if (MaskQuery(RelativeMouse.X / rect.Width, RelativeMouse.Y / rect.Height))
                {
                    render(rect, true);
                    if (nextMouseState.LeftButton == ButtonState.Released && previousMouseState.LeftButton == ButtonState.Pressed)
                        Action = handle;
                }
                else
                    render(rect, false);
            }
            else
                render(rect, false);
        }
    }
}
